
<template>
  <div class="accountList">
    <div class="searchBox">
      <el-form :model="searchForm" ref="searchFormRef">
        <el-row>
          <el-form-item prop="name">
            <div class="item">
              <span v-html="'姓名'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.name"
                placeholder="请输入姓名"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="loginName">
            <div class="item">
              <span v-html="'账号'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.loginName"
                placeholder="请输入账号"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="phone">
            <div class="item">
              <span v-html="'手机号'" class="nameSpan"></span>
              <el-input
                size="mini"
                v-model="searchForm.phone"
                placeholder="请输入手机号"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="roleId">
            <div class="item">
              <span v-html="'角色'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.roleId"
                placeholder="请选择角色"
                size="mini"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="status">
            <div class="item">
              <span v-html="'状态'" class="nameSpan"></span>
              <el-select filterable 
                clearable
                v-model="searchForm.status"
                placeholder="请选择状态"
                size="mini"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="searchClick"
              icon="el-icon-search"
              type="primary"
              size="mini"
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
              >重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="topBtn">
      <el-button
        size="mini"
        @click="addAccountClick"
        type="success"
        plain
        icon="el-icon-plus"
        v-has="'system:admin:add'"
        >新增员工</el-button
      >
    </div>

    <div class="tableBox" ref="tableBoxRef">
      <el-table
      :height="605"
        v-loading="tableLoading"
        :header-cell-style="{
          background: '#F8F8F8',
          color: '#333',
          fontSize: '16px',
          fontWeight: '700',
        }"
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          align="center"
          label="姓名"
           
        >
        </el-table-column>
        <el-table-column
          prop="loginName"
          align="center"
          label="账号"
           
        >
        </el-table-column>
        <el-table-column
          prop="email"
          align="center"
          label="邮箱"
           
        >
        </el-table-column>
        <el-table-column
          prop="phone"
          align="center"
          label="手机号"
           
        >
        </el-table-column>
           <el-table-column
          :show-overflow-tooltip="true"
          align="center"
          label="微信二维码"
          prop="wxQRCode"
          width="120"
        >
          <template slot-scope="scope" v-if='scope.row.wxQRCode'>
            <el-popover placement="left" trigger="click">
              <img
                :src="scope.row.wxQRCode"
                width="500px"
                @mousewheel="rollImg(this, scope.row.wxQRCode)"
                ref="bigImage"
              />
              <img
                slot="reference"
                :src="scope.row.wxQRCode"
                :alt="scope.row.wxQRCode"
                style="
                  height: 60px;
                  width: 60px;
                  cursor: pointer;
                "
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="roles"
          align="center"
          label="角色"
           
        >
          <template slot-scope="scope">
            {{ scope.row.roles.toString() }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              :disabled="permissions.indexOf('system:admin:status') == -1"
              @change="statusChange(scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
             <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'system:admin:cp'"
              @click="changePsdClick(scope.row)"
              >修改密码</el-button
            >
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              type="text"
              v-has="'system:admin:edit'"
              @click="editClick(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

       <el-card class="footer" v-if="total > 0">
         <div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[15, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      </el-card>
    </div>
    <el-dialog :close-on-click-modal="false" 
      title="修改密码"
      :visible.sync="psdVisible"
      width="500px"
      @close="psdDialogOpen"
      class="addEditAccountDialog"
    >
      <div class="content">
        <el-form   :model="psdForm"
          :rules="psdRules"
          ref="psdFormRef">
            <el-form-item prop="loginName" label="账号：">
            <div class="item">
              <el-input
              :disabled='true'
                size="mini"
                v-model="psdForm.loginName"
                placeholder="请输入账号"
              >
              </el-input>
            </div>
          </el-form-item>
            <el-form-item prop="newPassword" label="新密码：">
            <div class="item">
              <el-input
              type="password"
                size="mini"
                v-model="psdForm.newPassword"
                placeholder="请输入新密码"
              >
              </el-input>
            </div>
          </el-form-item>
            <el-form-item prop="repeatNewPassword" label="新密码：">
            <div class="item">
              <el-input
              type="password"
                size="mini"
                v-model="psdForm.repeatNewPassword"
                placeholder="请再次输入新密码"
              >
              </el-input>
            </div>
          </el-form-item>
           <el-form-item class="btns">
            <el-button size="mini" @click="closeClick"
              >取 消</el-button
            >
            <el-button
              v-clickForbidden
              size="mini"
              type="primary"
              @click="psdSaveClick"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- 新增/修改权限 -->
    <el-dialog :close-on-click-modal="false" 
    style="margin-top: -10vh;"
      :title="title"
      :visible.sync="addEditDialogVisible"
      width="500px"
      @open="addEditDialogOpen"
      class="addEditAccountDialog"
    >
      <div class="content">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditFormRef"
        >
          <el-form-item prop="name" label="姓名：">
            <div class="item">
              <el-input
                size="mini"
                v-model="addEditForm.name"
                placeholder="请输入员工姓名"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="loginName" label="账号：">
            <div class="item">
              <el-input
                size="mini"
                v-model="addEditForm.loginName"
                placeholder="请输入账号"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="email" label="邮箱：">
            <div class="item">
              <el-input
                size="mini"
                v-model="addEditForm.email"
                placeholder="请输入邮箱"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="phone" label="手机号码：">
            <div class="item">
              <el-input
                size="mini"
                @input="
                  addEditForm.phone = addEditForm.phone.replace(/[^\?\d]/g, '')
                "
                v-model="addEditForm.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              >
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="roleIds" label="角色：">
            <div class="item">
              <el-select filterable 
                clearable
                size="mini"
                v-model="addEditForm.roleIds"
                placeholder="请选择角色（可多选）"
                multiple
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item prop="wxQRCode" label="微信二维码：">
            <div class="item">
              <el-upload
                    :before-upload="beforeUpload"
                    accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif"
                    :action="$uploadUrl + '/2'"
                    list-type="picture-card"
                    :headers="postHead"
                    :show-file-list="false"
                    :on-success="handleProductPicSuccess"
                  >
                    <img
                      v-if="addEditForm.wxQRCode"
                      :src="addEditForm.wxQRCode"
                      style="width: 100px; height: 100px; display: block"
                    />
                    <i v-else class="el-icon-plus" style="position: absolute;top: 86px;left: 38px;"></i>
                  </el-upload>
            </div>
          </el-form-item>
          <el-form-item prop="status" label="是否启用：">
            <div class="item" style="margin-top: 8px">
              <el-switch
                style="display: block"
                v-model="addEditForm.status"
                active-color="#409eff"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>
          </el-form-item>
          <el-form-item class="btns">
            <el-button size="mini" @click="addEditDialogVisible = false"
              >取 消</el-button
            >
            <el-button
              v-clickForbidden
              size="mini"
              type="primary"
              @click="addEditDialogSaveClick"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'));
    } else {
     if (this.psdForm.repeatNewPassword !== '') {
       this.$refs.psdFormRef.validateField('repeatNewPassword');
     }
     callback();
    }
   };
   var validatePass2 = (rule, value, callback) => {
     if (value === '') {
       callback(new Error('请再次输入密码'));
     } else if (value !== this.psdForm.newPassword) {
       callback(new Error('两次输入密码不一致!'));
     } else {
       callback();
     }
   };
    return {
      postHead: { token: localStorage.token },
      searchForm: {
        name:"",
        loginName:"",
        phone:"",
        roleId:"",
        status:"",

      },
      statusOptions: [
        { label: "正常", value: 1 },
        { label: "禁用", value: 0 },
      ],
      tableLoading: false,
      tableHeight: 50,
      tableData: [],
      pageNum: 1,
      pageSize: 15,
      total: 0,
      addEditDialogVisible: false,
      psdVisible:false,
      psdForm:{
        loginName:'',
        id:"",
        newPassword:"",
        repeatNewPassword:""
      },
      addEditForm: {
        name: "",
        roleIds: [],
        phone: "",
        passwordInput: "",
        resetPasswordInput: "",
        wxQRCode:"",
        status:0,
      },
      addEditRules: {
        name: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" },
        ],
        loginName: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
      },
      psdRules:{
        password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { validator: validatePass, trigger: 'blur' }
     ],
     newPassword:[
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validatePass2, trigger: 'blur', required: true }
     ],
      },
      roleOptions: [],
      title: "新增员工",
      editId: "",
    };
  },
  created() {
    this.getAllRoleList();
    this.getStaffList();
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  methods: {
      beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 2;
      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        file = false;
        return file;
      }
      this.$message.warning("上传中,请稍等");
    },
    /**
     * 图片上传成功的事件
     * @param {*}
     */
    handleProductPicSuccess(res, file) {
      if (res.code == "00000") {
        this.addEditForm.wxQRCode = res.result.filePath;

        this.$message.success("上传成功");
      } else {
        this.$message.error(res.message);
      }
    },
    closeClick(){
       this.psdForm.newPassword=""
       this.psdForm.repeatNewPassword=""
    this.psdVisible=false;
    },
    psdSaveClick(){
      let data = {
        ...this.psdForm
      }
      this.$api.staffPsd(data).then(res=>{
        if(res.data.code=='00000'){
          this.$message.success("密码修改成功");
          this.psdVisible=false
        }
      })
       
    },
    resetClick() {
      this.$refs.searchFormRef.resetFields();
      this.pageNum = 1;
      this.getStaffList();
    },
    searchClick() {
      this.pageNum = 1;
      this.getStaffList();
    },
    /**
     * 获取所有角色列表
     * @param {*}
     */
    async getAllRoleList() {
      await this.$api.rolevalidList().then((res) => {
        if (res.data.code == "00000") {
          this.roleOptions = res.data.result;
        }
      });
    },

    /**
     * 获取员工列表
     * @param {*}
     */
    async getStaffList() {
      this.tableLoading = true;
      await this.$api
        .staffList({
          size: this.pageSize,
          page: this.pageNum,
          condition:{
            ...this.searchForm
          }
          
        })
        .then((res) => {
          if (res.data.code == "00000") {
            this.total = res.data.result.total;
            this.tableData = res.data.result.records;
            this.tableLoading = false;
          }
        });
    },

    /**
     * 新增员工
     * @param {*}
     */
    addAccountClick() {
      this.title = "新增员工";
      this.addEditDialogVisible = true;
    },
    changePsdClick(row){
     this.psdForm.loginName=row.loginName
     this.psdForm.id=row.id
      this.psdVisible=true;
    },
    /**
     * 编辑按钮
     * @param {*} row
     */
    async editClick(row) {
      this.title = "编辑员工";
      this.addEditDialogVisible = true;
      this.editId = row.id;
      await this.$api.staffDetail(this.editId).then((res) => {
        if (res.data.code == "00000") {
          this.$nextTick(() => {
            this.addEditForm = res.data.result;
          });
        }
      });
    },
    /**
     * 状态更新回调
     * @param {*} row
     */
    async statusChange(row) {
        try {
    const flag = row.status; // 点击之后的值
    row.status = row.status === 1 ? 0: 1; // switch点击前的状态
    const confirmTips = flag === 1 ? '启用' : '停用';
    const confirmTextTips = flag === 1 ? '允许' : '无法';
    //确认框
    const confirm = await this.$confirm(`${confirmTips}后，此账号${row.loginName}将${confirmTextTips}登录系统，确定${confirmTips}吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).catch(() => false);
    if (!confirm) return false;
   row.status = row.status === 1 ? 0: 1
    const res = await this.$api.staffStatus({id:row.id, status:row.status});
      if (res.data.code == "00000") {
        this.$message.success("状态更新成功");
        
      }
       this.getStaffList()
  } catch (error) {
     this.$message.error(error);
  }
    },

    /**
     * 切换页面大小
     * @param {*} val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getStaffList();
    },

    /**
     * 页码切换
     * @param {*} val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.getStaffList();
    },
  psdDialogOpen() {
      if (this.$refs.psdFormRef) this.$refs.psdFormRef.resetFields();
    },
    /**
     * 打开新增和修改的回调
     * @param {*}
     */
    addEditDialogOpen() {
      if (this.$refs.addEditFormRef) this.$refs.addEditFormRef.resetFields();
    },

    /**
     * 新增编辑保存按钮
     * @param {*}
     */
    addEditDialogSaveClick() {
      this.$refs.addEditFormRef.validate(async (boolean) => {
        if (boolean) {
          let data = {
            id: this.editId,
            name: this.addEditForm.name,
            email: this.addEditForm.email,
            loginName: this.addEditForm.loginName,
            phone: this.addEditForm.phone,
            roleIds: this.addEditForm.roleIds,
            wxQRCode:this.addEditForm.wxQRCode,
            status:this.addEditForm.status
          };
          if (this.title == "新增员工") {
              data.id=''
            await this.$api.addStaff(data).then((res) => {
              if (res.data.code == "00000") {
                this.$message.success("新增成功");
                this.getStaffList();
                this.addEditDialogVisible = false;
              }
            });
          } else {
           await this.$api.editAdmin(data).then((res) => {
              if (res.data.code == "00000") {
                this.$message.success("修改成功");
                this.getStaffList();
                this.addEditDialogVisible = false;
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.accountList {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  .searchBox {
    .el-row {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        margin-bottom: 0;
      }
      .item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        .nameSpan {
          padding-right: 10px;
          box-sizing: border-box;
          white-space: nowrap;
        }
        .el-input {
          width: 162px;
        }
      }
    }
  }
   .topBtn {
    margin: 10px 0;
text-align: right;
  }
  .addEditAccountDialog {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
    .btns {
      text-align: right;
      margin-bottom: 0;
    }
  }
}
/deep/.el-button--success.is-plain {
  color: #fff;
  border-color: #409eff;
  background-color: #409eff;
}
/deep/.el-form-item {
   margin-bottom: 12px;
}
/deep/.el-upload--picture-card {
  width: 102px;
  height: 102px;
  margin-top: 48px;
  display: block;
}

</style>